<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="listQuery" :model="listQuery" inline>
                <el-form-item label="查询类型" prop="type">
                    <el-select size="small" clearable class="filter-item" style="width: 160px" v-model="listQuery.type" placeholder="请选择查询类型">
                        <el-option v-for="item in typeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="listQuery.type==1" label="查询时间" prop="filterTime">
                    <el-date-picker size="small" clearable @change="setFilterTime" v-model="listQuery.filterTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item v-if="listQuery.type==2" label="开始月份" prop="startMonth">
                    <el-date-picker size="small" clearable v-model="listQuery.startMonth" type="month" placeholder="选择开始月份" format="yyyy-MM" value-format="yyyy-MM" style="width: 160px"></el-date-picker>
                </el-form-item>
                <el-form-item v-if="listQuery.type==2" label="结束月份" prop="endMonth">
                    <el-date-picker size="small" clearable v-model="listQuery.endMonth" type="month" placeholder="选择结束月份" format="yyyy-MM" value-format="yyyy-MM" style="width: 160px"></el-date-picker>
                </el-form-item>
                <el-form-item label="所属分组" prop="gid">
                    <el-select size="small" clearable class="filter-item" style="width: 160px" v-model="listQuery.gid" placeholder="请选择所属分组">
                        <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="display: block;">
                    <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
                    <el-button size="small" class="filter-item" type="danger" icon="el-icon" @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="height: 42px;line-height: 32px;">
            <el-button type="primary" icon="document" @click="handleDownload" :loading="downloadLoading" style="float: right;">下载报表</el-button>
        </div>
        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" stripe>
            <el-table-column width="80px" align="center" type="index" label="序号"></el-table-column>
            <el-table-column align="center" label="时间" prop="date"></el-table-column>
            <el-table-column align="center" label="分组" prop="groupName"></el-table-column>
            <el-table-column align="center" label="工作量" prop="clothesCnt"></el-table-column>
            <el-table-column align="center" label="工资金额" prop="salary"></el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleDetail(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[20,50,100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next" :total="total">
            </el-pagination>
        </div>

        <el-dialog title="查看详情" center :visible.sync="dialogDetail" @close="dialogDetail=false" width="80%">
            <detail :row="detailRow"></detail>
        </el-dialog>
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { factoryGroupList } from '@/api/factory'
  import { parseTime, formatSearchTime, formatMonthTime } from '@/utils'
  import exportExcel from '@/components/Excel/exportExcel'
  import { financeGroupSummary } from '@/api/finance'
  import detail from '@/views/salary/groupDetail'

  export default {
    name: 'SalaryGroup',
    data() {
      return {
        tableKey: 0,
        list: [],
        groupOptions: [],
        total: null,
        listLoading: false,
        listQuery: {
          page: 1,
          size: 20,
          type: '',
          gid: '',
          startTime: '',
          endTime: '',
          filterTime: [],
          startMonth: '',
          endMonth: ''
        },
        typeOptions: [{ name: '按日查询', id: 1 }, { name: '按月查询', id: 2 }],
        downloadLoading: false,
        dialogDetail: false,
        detailRow: ''
      }
    },
    components: {
      exportExcel,
      detail
    },
    computed: {
      ...mapGetters([
        'fid'
      ])
    },
    created: function() {
      this.fetchGroup()
    },
    filters: {
      parseTime
    },
    methods: {
      fetchGroup() {
        factoryGroupList({ page: 1, size: 500 }).then(response => {
          this.groupOptions = response.data && response.data.list || []
        })
      },
      getList() {
        let startTime = ''
        let endTime = ''
        if (!this.listQuery.type) {
          this.$message({ message: '请先选择查询类型', type: 'error', showClose: true })
          return
        }
        if (this.listQuery.type === 1) {
          if (!this.listQuery.startTime || !this.listQuery.endTime) {
            this.$message({ message: '请先选择查询起止时间', type: 'error', showClose: true })
            return
          }
          startTime = formatSearchTime(this.listQuery.startTime + ' ', true)
          endTime = formatSearchTime(this.listQuery.endTime + ' ')
        }
        if (this.listQuery.type === 2) {
          if (!this.listQuery.startMonth || !this.listQuery.endMonth) {
            this.$message({ message: '请先选择查询起止月份', type: 'error', showClose: true })
            return
          }
          if (this.listQuery.startMonth > this.listQuery.endMonth) {
            this.$message({ message: '开始月份不能大于结束月份', type: 'error', showClose: true })
            return
          }
          startTime = formatMonthTime(this.listQuery.startMonth, true)
          endTime = formatMonthTime(this.listQuery.endMonth)
        }
        this.listLoading = true
        var query = {
          page: this.listQuery.page,
          size: this.listQuery.size,
          type: this.listQuery.type,
          gid: this.listQuery.gid,
          startTime: startTime,
          endTime: endTime
        }
        financeGroupSummary(query).then(response => {
          this.list = response.data && response.data.list || []
          this.list.forEach((item, index) => {
            item.startTime = query.startTime
            item.endTime = query.endTime
            item.searchType = query.type
          })
          this.total = Number.parseInt(response.data.count)
          this.listLoading = false
        }).catch(e => {
          this.listLoading = false
        })
      },
      setFilterTime() {
        if (this.listQuery.filterTime && this.listQuery.filterTime.length) {
          this.listQuery.startTime = this.listQuery.filterTime[0]
          this.listQuery.endTime = this.listQuery.filterTime[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetFilter() {
        this.$refs['listQuery'].resetFields()
        this.setFilterTime()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDownload() {
        let startTime = ''
        let endTime = ''
        if (!this.listQuery.type) {
          this.$message({ message: '请先选择查询类型', type: 'error', showClose: true })
          return
        }
        if (this.listQuery.type === 1) {
          if (!this.listQuery.startTime || !this.listQuery.endTime) {
            this.$message({ message: '请先选择查询起止时间', type: 'error', showClose: true })
            return
          }
          startTime = formatSearchTime(this.listQuery.startTime + ' ', true)
          endTime = formatSearchTime(this.listQuery.endTime + ' ')
        }
        if (this.listQuery.type === 2) {
          if (!this.listQuery.startMonth || !this.listQuery.endMonth) {
            this.$message({ message: '请先选择查询起止月份', type: 'error', showClose: true })
            return
          }
          if (this.listQuery.startMonth > this.listQuery.endMonth) {
            this.$message({ message: '开始月份不能大于结束月份', type: 'error', showClose: true })
            return
          }
          startTime = formatMonthTime(this.listQuery.startMonth, true)
          endTime = formatMonthTime(this.listQuery.endMonth)
        }
        this.downloadLoading = true
        var query = {
          page: 1,
          size: 1000,
          type: this.listQuery.type,
          gid: this.listQuery.gid,
          startTime: startTime,
          endTime: endTime
        }
        financeGroupSummary(query).then(response => {
          var excelList = response.data && response.data.list || []
          if (!excelList || !excelList.length) {
            this.$message({ message: '没有可下载的报表', type: 'error', showClose: true })
            this.downloadLoading = false
            return
          }
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['时间', '分组', '工作量', '工资金额']
            const filterVal = ['date', 'groupName', 'clothesCnt', 'salary']
            const data = this.formatJson(filterVal, excelList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '小组工资' + parseTime(query.startTime, '{y}-{m}-{d}') + '至' + parseTime(query.endTime, '{y}-{m}-{d}'),
              autoWidth: true
            })
            this.downloadLoading = false
          })
        }).catch(e => {
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          return v[j]
        }))
      },
      handleDetail(row) {
        this.detailRow = row
        this.dialogDetail = true
      }
    }
  }
</script>

<style scoped>
    .el-range-editor.el-input__inner {
        width: 273px;
        padding: 3px;
    }
</style>
